package com.mds.group.four.test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PictureCallback;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class CameraActivity extends Activity {
	String mRootPath;
	LinearLayout mTakePicture;
	LinearLayout mImageLayout;
	ImageView mReview;
	CameraSurface mSurface;
	RelativeLayout mRecAudio;
	int mPicWidth, mPicHeight;
	int mSelect;
	String mLastPicture = "";
	String FileName = "";
	String Path = null;
	static final String PICFOLDER = "SHCamera";
	static final int TAKEDELAY = 300;
	Context mMainContext;
	LinearLayout mLinear;
	EditText mEditText;
	private AppDAO db;
	
	MediaRecorder mRecorder = null;
	Button mStartBtn, mPlayBtn;
	boolean mIsStart;
	boolean mIsReady = true;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.camera);
		
		if (db == null) db = new AppDAO(CameraActivity.this);
		
//		Intent i = getIntent();
//		FileName = i.getStringExtra(TestActivity.title);
//		Log.i("FileName", "FileName : " + FileName);
		
		mMainContext = this;
		
		// SD 카드가 없을 경우 에러 처리한다.
		String ext = Environment.getExternalStorageState();
		if (ext.equals(Environment.MEDIA_MOUNTED) == false) {
			Toast.makeText(this, "SD 카드가 반드시 필요합니다.", 1).show();
			finish();
			return;
		}
		
		
//		mRootPath="/";

		mRootPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
		File fRoot = new File(mRootPath);
		if (fRoot.exists() == false) {
			if (fRoot.mkdir() == false) {
				Toast.makeText(this, "사진을 저장할 폴더가 없습니다.", 1).show();
				finish();
				return;
			}
		}
		
		// 프리퍼런스에서 크기 읽어옴.
		SharedPreferences pref = getSharedPreferences("SHCamera",0);
		mPicWidth = pref.getInt("PicWidth", -1);
		mPicHeight = pref.getInt("PicHeight", -1);

		// 버튼들의 클릭리스너 지정.
		mTakePicture = (LinearLayout)findViewById(R.id.takepicture);
		mReview = (ImageView)findViewById(R.id.imgreview);
		mSurface = (CameraSurface)findViewById(R.id.preview);
		mLinear = (LinearLayout)findViewById(R.id.layout_reg);
		mImageLayout = (LinearLayout)findViewById(R.id.imagelayout);
		mRecAudio = (RelativeLayout)findViewById(R.id.recaudio);
		
		findViewById(R.id.btntake).setOnClickListener(mTakeClick);
		
//		findViewById(R.id.btnsize).setOnClickListener(mSizeClick);
//		findViewById(R.id.btnreview).setOnClickListener(mReviewClick);
//		((CheckBox)findViewById(R.id.btnmacro)).setOnCheckedChangeListener(toggleMacro);
		
		// 단어등록 후 촬영 모드로 전환.
		findViewById(R.id.reg_title).setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Log.i("----", "단어 등록... ");
				EditText et = (EditText) findViewById(R.id.edit_title);
				FileName = et.getText().toString();
				Log.i("----", "file name setting :"+FileName+"   length :"+ FileName.length());
				if(FileName.length() != 0) {
					findViewById(R.id.layout_reg).setVisibility(View.INVISIBLE);
					mTakePicture.setVisibility(View.VISIBLE);
				}
				else {
					Toast ts = Toast.makeText(v.getContext(), "단어를 입력하세요.", Toast.LENGTH_SHORT);
					ts.setGravity(Gravity.TOP, 0, 20);
					ts.show();
				}
	    	}
		});
		// 녹음화면으로 넘김.
		findViewById(R.id.reg_image).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				mSurface.mCamera.stopPreview();
				mImageLayout.setVisibility(View.GONE);
				mReview.setVisibility(View.GONE);
				findViewById(R.id.preview).setVisibility(View.GONE);
				mRecAudio.setVisibility(View.VISIBLE);
			}
		});
		
		// 녹음.
		findViewById(R.id.recbt).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.i("----", "FileName: " + FileName);
				Button mStartBtn = (Button)findViewById(R.id.recbt);
				if (!mIsStart) {
//					String sd = Environment.getExternalStorageDirectory().getAbsolutePath();
//					Calendar calendar = Calendar.getInstance();
//					String FileName = String.format("SH%02d%02d%02d-%02d%02d%02d.3gp", 
//							calendar.get(Calendar.YEAR) % 100, calendar.get(Calendar.MONTH)+1, 
//							calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.HOUR_OF_DAY), 
//							calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND));
					Path = mRootPath + "/TestApp/" + "aud_" + FileName;
					if (mRecorder == null) {
						mRecorder = new MediaRecorder();
					} else {
						mRecorder.reset();
					}
					Log.e("audioreg", "mRecorder:"+mRecorder+" filename:"+Path);
					mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
					mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
					mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
					mRecorder.setOutputFile(Path);
					try {
						mRecorder.prepare();
					} catch (IllegalStateException e) {
						Toast.makeText(CameraActivity.this, "IllegalStateException", 1).show();
					} catch (IOException e) {
						Toast.makeText(CameraActivity.this, "IOException", 1).show();
					}
					mRecorder.start();
					mIsStart = true;
					mStartBtn.setText("Stop");
				} else {
					mRecorder.stop();
					mRecorder.release();
					mRecorder = null;
					mIsStart = false;
					mStartBtn.setText("Start");
					findViewById(R.id.recplay).setVisibility(View.VISIBLE);
					findViewById(R.id.regdb).setVisibility(View.VISIBLE);
				}
			}
		});
		
		// 음성 재생.
		findViewById(R.id.recplay).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (Path.length() == 0 || mIsStart) {
					Toast.makeText(CameraActivity.this, "녹음을 먼저하세요.", 0).show();
					return;
				}
				MediaPlayer player = new MediaPlayer();
				try {
					player.setDataSource(Path);
					player.prepare();
					player.start();
				} catch (Exception e) {
					Toast.makeText(CameraActivity.this, "error : " + e.getMessage(), 0).show();
				}
			}
		});
		
		// db 등록.
		findViewById(R.id.regdb).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				db.insertNote(FileName);
				finish();
			}
		});
	}
	public void onDestroy() {
		super.onDestroy();
	}
		
	// 사진 확인상태에서 Back누르면 촬영모드로 전환, 촬영상태에서 Back 누르면 단어 입력모드로 전환.
	public boolean onKeyUp (int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && mReview.getVisibility() == View.VISIBLE) {
			mReview.setVisibility(View.GONE);
			mTakePicture.setVisibility(View.VISIBLE);
			mSurface.mCamera.startPreview();
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_BACK && mTakePicture.getVisibility() == View.VISIBLE) {
			mTakePicture.setVisibility(View.GONE);
			mSurface.mCamera.stopPreview();
			mLinear.setVisibility(View.VISIBLE);
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_BACK && mRecAudio.getVisibility() == View.VISIBLE) {
			mRecAudio.setVisibility(View.GONE);
			mTakePicture.setVisibility(View.VISIBLE);
			mSurface.mCamera.startPreview();
			return true;
		} else {
			super.onKeyUp(keyCode, event);
			return false;
		}
	}

	// 사진 촬
	Button.OnClickListener mTakeClick = new Button.OnClickListener() {
		public void onClick(View v) {
			if(mIsReady){
				mIsReady = false;
				mSurface.mCamera.autoFocus(mAutoFocus);
			}
		}
	};

	// 포커싱 성공하면 촬영.
	AutoFocusCallback mAutoFocus = new AutoFocusCallback() {
		public void onAutoFocus(boolean success, Camera camera) {
			if (success) {
				mTakePicture.postDelayed(new Runnable() {
					public void run() {
						mSurface.mCamera.takePicture(null, null, mPicture);
					}
				}, TAKEDELAY);
			} else {
				Toast.makeText(mMainContext, "초점을 잡을 수 없습니다.", 1).show();
			}
		}
	};

	// 사진저장, 날짜와 시간으로 파일명 결졍하고 저장후 미디어 스캔 실행.
	PictureCallback mPicture = new PictureCallback() {
		public void onPictureTaken(byte[] data, Camera camera) {
//			Calendar calendar = Calendar.getInstance();
//			String FileName = String.format("SH%02d%02d%02d-%02d%02d%02d.jpg", 
//					calendar.get(Calendar.YEAR) % 100, calendar.get(Calendar.MONTH)+1, 
//					calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.HOUR_OF_DAY), 
//					calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND));
			String path = mRootPath + "/TestApp/" + "img_" + FileName;

			File file = new File(path);
			FileOutputStream fos = null;
			try {
				fos = new FileOutputStream(file);
				fos.write(data);
				fos.flush();
			} catch (Exception e) {
				Toast.makeText(mMainContext, "파일 저장중 에러 발생 : " + 
						e.getMessage(), Toast.LENGTH_LONG).show();
				Log.e("-----------------------", "파일 저장중 에러 발생 :"+e.getMessage());
				return;
			} finally {
				if(fos != null)
					try {
						fos.close();
					} catch(Exception e){}
			}

			// 스캐닝 요청.
			Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
			Uri uri = Uri.parse("file://" + path);
			intent.setData(uri);
			sendBroadcast(intent);

			mLastPicture = path;
//			mSurface.mCamera.startPreview();
			
			// 촬영 후 미리보기.
			mImageLayout.setVisibility(View.VISIBLE);
			mReview.setVisibility(View.VISIBLE);
			mTakePicture.setVisibility(View.GONE);
			try {
//				BitmapFactory.Options opt = new BitmapFactory.Options();
//				opt.inSampleSize = 4;
//				Bitmap bm = BitmapFactory.decodeFile(mLastPicture, opt);
				Bitmap bm = BitmapFactory.decodeFile(mLastPicture, null);
				
				/*Matrix matrix = new Matrix(); //2013-10-04
				matrix.postRotate(90); // 회전.
				 
				// 이미지를 회전시킨다.
				Bitmap resizeBitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
				
				mReview.setImageBitmap(resizeBitmap);*/
				mReview.setImageBitmap(bm);
//				mReview.setVisibility(View.VISIBLE);
			}
			catch (OutOfMemoryError e) {
				Toast.makeText(mMainContext,"이미지를 읽을 수 없습니다.", 0).show();
			}
			mIsReady = true;
//			mReview.setOnTouchListener(new View.OnTouchListener() {
//				public boolean onTouch(View v, MotionEvent event) {
//					mReview.setVisibility(View.GONE);
//					mTakePicture.setVisibility(View.VISIBLE);
//					return false;
//				}
//			});	
		}
	};
	
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
	
		menu.add(0,1,0,"소개");
		menu.add(0,2,0,"종료");

		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 1:
    		new AlertDialog.Builder(this)
    		.setTitle("프로그램 소개")
    		.setMessage("이 프로그램은 필수 기능만 제공하는 카메라입니다. 기존 카메라는 화면의 셔터 버튼을 " + 
    				"놓을 때 장비의 떨림으로 인해 사진의 정확도가 떨어지나 이 프로그램은 터치를 놓은 후 초점을 " + 
    				"맞추고 잠시 대기 후 사진을 찍어 선명도를 극대화합니다. 잘생긴 사람은 누구나 무료로 사용할 수 있습니다.")
    		.setPositiveButton("닫기", null)
    		.show();
			return true;
		case 2:
			finish();
			System.exit(0);
			return true;
		}
		return false;
	}
}
